package jee.boot.common.utils;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 读取Http请求
 */
public class HttpServletHolder {
    /**
     * 默认语言
     */
    public static final String DEFAULT_LANGUAGE = "zh-CN";


    /**
     * 获取当前请求session
     *
     * @return
     */
    public static HttpServletRequest getHttpServletRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null && requestAttributes instanceof ServletRequestAttributes) {
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            return request;
        }
        return null;

    }

    /**
     * 获取当前请求session
     *
     * @return
     */
    public static HttpSession getHttpSession() {
        return getHttpServletRequest().getSession();
    }

    /**
     * 当前请求的url
     * @return
     */
    public static String getUri(){
        HttpServletRequest httpServletRequest = getHttpServletRequest();
        if(httpServletRequest!=null){
            return httpServletRequest.getRequestURI();
        }
        return null;
    }
    /**
     * 从request中读取多语言设置
     *
     * @return
     */
    public static String getLanguage() {
        // 从请求中获语言
        HttpServletRequest request = getHttpServletRequest();
        if (request != null) {
            String language = request.getHeader("Language");
            if (StringUtils.isNotBlank(language)) {
                return language;
            }
        }
        // 从线程中获取语言
        String language = JeeBootContext.get(JeeBootContext.LANGUAGE);
        if(language!=null){
            return language;
        }
        // 返回默认语言
        return DEFAULT_LANGUAGE;
    }

    /**
     * 获取表后缀,主要用于缓存以及表名的拼接,
     *
     * @return
     */
    public static String getTableSuffix() {
        String language = getLanguage();
        // 如果是默认语言,则直接返回空尾缀,使用中文对应的表,以及后缀
        if (StringUtils.equals(DEFAULT_LANGUAGE, language)) {
            return "";
        }
        return "_" + StringUtils.replace(language,"-","_");
    }
}
